/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-25 16:32:13
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2023-10-20 16:28:44
 */
import * as CryptoJS from 'crypto-js'

type encryptionType = {
	data: any
	type?: string
	param: any
	key?: string
}
let theKey = 'ZYXBsZaWQyMDIxMjAyMTExMQ=='
const toParser = (str) => {
	let list = str.split('')
	list.shift()
	list.splice(4,1)
	let str1 = list.join('')
	str1 = atob(str1)
	return str1
}
theKey= toParser(theKey)
export const encryption = (params: encryptionType) => {
	let { data, type, param, key=theKey } = params
	const result = JSON.parse(JSON.stringify(data))
	if (type === 'Base64') {
		param.forEach((ele) => {
			result[ele] = btoa(result[ele])
		})
	} else {
		param.forEach((ele) => {
			var data = result[ele]
			key = CryptoJS.enc.Latin1.parse(key)
			var iv = key
			// 加密
			var encrypted = CryptoJS.AES.encrypt(`${data}`, key, {
				iv: iv,
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.ZeroPadding,
			})
			result[ele] = encrypted.toString()
		})
	}
	return result
}

export function encryp(data, key = 2023, iv = 2023) {
	if (typeof data === 'object') {
		try {
			data = JSON.stringify(data)
		} catch (error) {
			console.log('error:', error)
		}
	}
	const dataHex = CryptoJS.enc.Utf8.parse(data) // 需要加密的数据
	const keyHex = CryptoJS.enc.Utf8.parse(key) // 秘钥
	const ivHex = CryptoJS.enc.Utf8.parse(iv) // 偏移量
	const encrypted = CryptoJS.AES.encrypt(dataHex, keyHex, {
		iv: ivHex,
		mode: CryptoJS.mode.CBC, // 加密模式
		padding: CryptoJS.pad.Pkcs7,
	})
	let encryptedVal = encrypted.ciphertext.toString()
	return encryptedVal //  返回加密后的值
}
// 解密数据
export function decrypt(encryptedVal, key = 2023, iv = 2023) {
	// 统一将传入的字符串转成UTF8编码
	let encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedVal)
	let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
	const keyHex = CryptoJS.enc.Utf8.parse(key) // 秘钥
	const ivHex = CryptoJS.enc.Utf8.parse(iv) // 偏移量
	let decrypt = CryptoJS.AES.decrypt(srcs, keyHex, {
		iv: ivHex,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7,
	})

	let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
	return decryptedStr.toString()
}

// 对象字符串处理后加密
export const encrypDataStr = (data) => {
	function stringifyFunction(obj) {
		let newobj = JSON.parse(JSON.stringify(obj))
		for (let key in obj) {
			if (obj[key] instanceof Function) {
				newobj[key] = obj[key].toString().replace(/[\n\t]/g, '')
				continue
			}
			if (obj[key] instanceof Object) {
				newobj[key] = stringifyFunction(obj[key])
			}
		}
		return newobj
	}

	function objectToString(obj) {
		let _object = stringifyFunction(obj)
		return JSON.stringify(_object)
	}
	return encryp(objectToString(data))
}
export const decryptJson = (enrypStr) => {
	return JSON.parse(decrypt(enrypStr))
}

export const md5 = (str) => {
	return CryptoJS.MD5(str).toString().toLowerCase()
}
